class StatController < ApplicationController
  def get_running_result(project_setting, running_stocks, market_stock_id, market_stock_type, note)
    result = Array.new
    result = result << get_basic_setting(project_setting, running_stocks.size, note)
    if project_setting.mm_flag=='Y'
      begin
        result = result << get_mm_result(project_setting, running_stocks, market_stock_id, market_stock_type)
      rescue
        result = result << "Error in MM module"
      end
    end
    if project_setting.sw_flag=='Y'
      begin
        result = result << get_sw_result(project_setting, running_stocks, market_stock_id, market_stock_type)
      rescue
        result = result << "Error in SW module"
      end
    end
    if project_setting.bn_flag=='Y'
      begin
        result = result << get_bn_result(project_setting, running_stocks, market_stock_id, market_stock_type)
      rescue
        result = result << "Error in BN module"
      end
    end
    if project_setting.hm_flag=='Y'
      begin
        result = result << get_hm_result(project_setting, running_stocks, market_stock_id, market_stock_type)
      rescue
        result = result << "Error in HM module"
      end
    end
    return result.join("\n")
  end

  def get_basic_setting(project_setting, n, note)
    begin
      result = Array.new
      result = result << "<h3>#{note}</h3>Run at: #{Time.now}"
      result = result << "Estimation Window: (#{project_setting.min_est},#{project_setting.max_est}) &nbsp;&nbsp; Event Window: (#{project_setting.min_event},#{project_setting.min_event})"
      result = result << "N: #{n}"
      return result.join('<br/>')
    rescue
      return ''
    end
  end

  def cal_sse(est_market)
    require 'statsample'
    sse = nil
    begin
      v = est_market.to_scale
      sse = v.sum_of_squares
    rescue
    end
    return sse
  end

  def cal_amr(est_market)
    require 'statsample'
    amr = nil
    begin
      v = est_market.to_scale
      amr = v.mean
    rescue
    end
    return amr
  end

  def cal_sde(est_stock, est_market, a, b)
    require 'statsample'
    sde = nil
    begin
      ar_array = Array.new
      est_stock.each_with_index do |e,i|
        est_value = a + (b * est_market[i])
        ar_array = ar_array << (e - est_value)
      end
      v = ar_array.to_scale
      sde = v.standard_deviation_sample
    rescue
    end
    return sde
  end

  def cal_sde_sw(est_stock, est_ri_cal)
    require 'statsample'
    sde = nil
    begin
      ar_array = Array.new
      est_stock.each_with_index do |e,i|
        est_value = est_ri_cal[i]
        ar_array = ar_array << (e - est_value)
      end
      v = ar_array.to_scale
      sde = v.standard_deviation_sample
    rescue
    end
    return sde
  end

  def cal_sre(ae, sse, amr, sde, rm, t)
    sre = nil
    begin
      sre = ae / (sde * Math.sqrt(1.0+(1.0/t)+(((rm-amr)**2)/sse)))
    rescue
    end
    return sre
  end

  def cal_partell(sr_all, i, t, total_k=0)
    z = ''
    begin
      sum = 0.0
      div = 0.0
      sr_all.each{ |k,v|
        sum += v[i]
        div += ((t - 2)/(t - 4))
      }
      cal = sum / Math.sqrt(div)
      z = "#{get_t_test_star(sr_all.size-total_k,cal)} #{'%.4f' % cal}"
    rescue
      z = 'Error'
    end
    return z
  end

  def cal_boehmer(sr_all, i, total_k=0)
    z = ''
    begin
      sum = 0.0
      div = 0.0
      n = sr_all.size
      sr_all.each{ |k,v|
        sum += v[i]
      }
      sr_all.each{ |k,v|
        div += (v[i] - (sum/n))**2
      }
      cal = (sum/n) / Math.sqrt(div/(n*(n-1)))
      z = "#{get_t_test_star(n-total_k,cal)} #{'%.4f' % cal}"
    rescue
      z = 'Error'
    end
    return z
  end

  def cal_signtest(ar_all, i, total_k=0)
    z = ''
    begin
      w = 0
      p_hat = 0
      n = ar_all.size
      ar_all.each{ |k,v|
        if v[i]>0
          w += 1
        end
        ph = 0
        v.each do |e|
          if e>0
            ph += 1
          end
        end
        ph = ph/v.size
        p_hat += ph
      }
      p_hat = p_hat/n
      cal = (w - (n*p_hat)) / Math.sqrt(n*p_hat*(1-p_hat))
      z = "#{get_t_test_star(n-total_k,cal)} #{'%.4f' % cal}"
    rescue
      z = 'Error'
    end
    return z
  end

  def cal_rank(total_ar)
    require 'statsample'
    rank = nil
    begin
      v = total_ar.to_scale
      rank = v.ranked.to_a
    rescue
    end
    return rank
  end

  def cal_ranktest(rank_all, i, est_size, event_size, total_k=0)
    require 'statsample'
    z = ''
    begin
      t = est_size+event_size
      n = rank_all.size
      ki = 0.5 + t/2
      sum = 0
      sum_square = 0
      sum_sk = 0
      rank_all.each{ |k,v|
        kit = v[est_size+i]
        sum += kit - ki
        sum_square += (kit - ki)**2
      }
      for j in 1..t do
        sum_sk += sum_square/(n**2)
      end
      sk = Math.sqrt(sum_sk/t)
      cal = (sum/n) / sk
      z = "#{get_t_test_star(n-total_k,cal)} #{'%.4f' % cal}"
    rescue
      z = 'Error'
    end
    return z
  end

  def get_mm_result(project_setting, running_stocks, market_stock_id, market_stock_type)
    require 'statsample'
    result = Array.new
    result = result << "<h3>Market Model</h3>"
    result = result << "Estimated Coefficients<hr/>"
    ar_all = Hash.new
    car_all = Hash.new
    sr_all = Hash.new
    rank_all = Hash.new
    aar = Array.new
    caar = Array.new
    compute_word = Array.new
    leadlag_size = 0
    if project_setting.leadlag_size
      leadlag_size = project_setting.leadlag_size
    end
    running_stocks.each_with_index do |rs,j|
      est_stock = Array.new
      est_market = Array.new
      event_stock = Array.new
      event_market = Array.new
      stock_symbol = 'S'
      if rs.stock_type=='S'
        stock_symbol = rs.stock.s_symbol
        est_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        event_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_stock = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      else
        stock_symbol = UserStock.find(rs.user_stock_id).s_symbol
        est_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        event_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_stock = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      end
      if market_stock_type=="System's"
        est_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        event_market = event_market[leadlag_size..event_market.size-1-leadlag_size]
      else
        est_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        event_market = event_market[leadlag_size..event_market.size-1-leadlag_size]
      end
      sr = nil
      begin
        sr = Statsample::Regression.simple(est_market.to_scale, est_stock.to_scale)
      rescue
      end
      sign = ''
      if sr
        if sr.b>=0
          sign = '+'
        end
        result = result << "#{stock_symbol}: Ri = #{'%.4f' % sr.a}#{sign}#{'%.4f' % sr.b}Rm, r^2 = #{'%.4f' % sr.r2}"
        ar_array = Array.new
        car_array = Array.new
        sr_array = Array.new
        rank_array = Array.new
        total_ar = Array.new
        sse = cal_sse(est_market)
        amr = cal_amr(est_market)
        sde = cal_sde(est_stock, est_market, sr.a, sr.b)
        est_stock.each_with_index do |es,i|
          ri_cal = sr.y(est_market[i])
          total_ar = total_ar << es - ri_cal
        end
        event_stock.each_with_index do |es,i|
          ri_cal = sr.y(event_market[i])
          ar_array[i] = es - ri_cal
          total_ar = total_ar << es - ri_cal
          sr_array[i] = cal_sre(ar_array[i], sse, amr, sde, event_market[i], est_stock.size)
        end
        rank_array = cal_rank(total_ar)
        ar_array.each_with_index do |ar,i|
          if i==0
            car_array[i] = ar
          else
            car_array[i] = car_array[i-1] + ar
          end
        end
        compute_word = compute_word << "s#{j}"
        ar_all["s#{j}"] = ar_array
        car_all["s#{j}"] = car_array
        sr_all["s#{j}"] = sr_array
        rank_all["s#{j}"] = rank_array
      else
        result = result << "#{stock_symbol}: Error in Estimation Process, Excluded from Calculation"
      end
    end

    min_event_date = project_setting.min_event
    event_size = project_setting.max_event - project_setting.min_event + 1
    estimation_size = project_setting.max_est - project_setting.min_est + 1

    for i in 1..event_size do
      mean = 0
      mean2 = 0
      total1 = 0
      total2 = 0
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          mean += ar_all["s#{j}"][i-1]
          total1 += 1
        end
        if car_all["s#{j}"]
          mean2 += car_all["s#{j}"][i-1]
          total2 += 1
        end
      end
      mean = mean/total1
      mean2 = mean2/total2
      aar[i-1] = mean
      caar[i-1] = mean2
    end

    table = "<font color='red'>*** : sig. at &alpha;=0.01, ** : sig. at &alpha;=0.05, * : sig. at &alpha;=0.1</font>"
    table += "<table class='basic_table'>"
    table += "<tr align='center'><th>Day</th><th>AAR</th>"
    if project_setting.aar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    table += "<th>CAAR</th>"
    if project_setting.caar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    if project_setting.sign_test=='Y'
      table += "<th>Sign Test<br/>(t)</th>"
    end
    if project_setting.rank_test=='Y'
      table += "<th>Rank Test<br/>(t)</th>"
    end
    if project_setting.sd_ar_test=='Y'
      table += "<th>Standardized<br/>abnormal return(t)</th>"
    end
    if project_setting.sd_cr_test=='Y'
      table += "<th>Standardized<br/>cross-sectional return(t)</th>"
    end
    table += "</tr>"

    labels = Array.new
    event_index = 0
    for i in 1..event_size do
      table += "<tr align='right'>"
      labels = labels << "#{min_event_date+i-1}"
      if  min_event_date+i-1==0
        event_index = i
      end
      table += "<td align='center'>#{min_event_date+i-1}</td>"
      table += "<td>#{begin '%.4f' % aar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          t_v[j] = ar_all["s#{j}"][i-1]
        end
      end

      if project_setting.aar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end

      table += "<td>#{begin '%.4f' % caar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if car_all["s#{j}"]
          t_v[j] = car_all["s#{j}"][i-1]
        end
      end

      if project_setting.caar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end
      if project_setting.sign_test=='Y'
        table += "<td>#{cal_signtest(ar_all,i-1)}</td>"
      end
      if project_setting.rank_test=='Y'
        table += "<td>#{cal_ranktest(rank_all,i-1,estimation_size,event_size)}</td>"
      end
      if project_setting.sd_ar_test=='Y'
        table += "<td>#{cal_partell(sr_all,i-1,estimation_size,2)}</td>"
      end
      if project_setting.sd_cr_test=='Y'
        table += "<td>#{cal_boehmer(sr_all,i-1,2)}</td>"
      end

      table += "</tr>"
    end
    table += "</table>"

    result = result << ""
    result = result << "Test Results<hr/>"
    result = result << table
    result = result << ""
    if project_setting.aar_diagram=='Y'
      begin
        result = result << add_aar_chart_section(labels, aar, event_index, 'aar_mm', 600, 350)
      rescue
        result = result << "Error in AAR Diagram"
      end
    end
    if project_setting.caar_diagram=='Y'
      begin
        result = result << add_caar_chart_section(labels, caar, event_index, 'caar_mm', 600, 350)
      rescue
        result = result << "Error in CAAR Diagram"
      end
    end
    result = result << ""
    if project_setting.ar=='Y'
      begin
        result = result << add_ar_table(ar_all, running_stocks, event_size, min_event_date, "AR Table")
      rescue
        result = result << "Error in AR table"
      end
    end
    result = result << ""
    if project_setting.car=='Y'
      begin
        result = result << add_ar_table(car_all, running_stocks, event_size, min_event_date, "CAR Table")
      rescue
        result = result << "Error in CAR table"
      end
    end
    result = result << ""
    return result.join("\n")
  end

  def add_ar_table(ar_all, running_stocks, event_size, min_event_date, title)
    result = Array.new
    result = result << "#{title}"
    table = ""
    table += "<table class='basic_table'>"
    table += "<tr align='center'><th></th>"
    running_stocks.each do |rs|
      if rs.stock_type=='S'
        s = Stock.find(:first, :conditions=>["id=?", rs.stock_id])
        if s
          table += "<th>#{s.s_symbol}</th>"
        end
      else
        s = UserStock.find(:first, :conditions=>["id=?", rs.user_stock_id])
        if s
          table += "<th>#{s.s_symbol}</th>"
        end
      end
    end
    table += "</tr>"
    table += "<tr><th>Day</th>"
    running_stocks.each do |rs|
      table += "<th>#{rs.event_date}</th>"
    end
    table += "</tr>"
    for i in 1..event_size do
      table += "<tr>"
      table += "<td align='center'>#{min_event_date+i-1}</td>"
      running_stocks.each_with_index do |rs,j|
        table += "<td align='right'>#{begin '%.4f' % ar_all["s#{j}"][i-1] rescue '' end}</td>"
      end
      table += "</tr>"
    end
    table += "</table>"
    result = result << table
    return result.join("\n")
  end

  def add_chart_section_bk(labels, aar, caar, event_index, chart_div, width, height)
    chart = "<span id='#{chart_div}'>Now Loading...</span>[newline]"
    chart += "<script type='text/javascript'>[newline]"
    chart += "FusionCharts.setCurrentRenderer('javascript');[newline]"
    chart += "var chart = new FusionCharts('/Charts/ZoomLine.swf','Chart#{chart_div}','#{width}','#{height}','0','1');[newline]"
    chart += "chart.setXMLData(\"#{aar_chart_xml(labels, aar, caar, event_index, chart_div, 0)}\");[newline]"
    chart += "chart.render('#{chart_div}');[newline]"
    chart += "</script>[newline]"
  end

  def add_aar_chart_section(labels, aar, event_index, chart_div, width, height)
    chart = "<span id='#{chart_div}'>Now Loading...</span>[newline]"
    chart += "<script type='text/javascript'>[newline]"
    chart += "var chart = new FusionCharts('/Charts/ZoomLine.swf','Chart#{chart_div}','#{width}','#{height}','0','1');[newline]"
    chart += "chart.setXMLData(\"#{aar_chart_xml(labels, aar, event_index, chart_div, 1)}\");[newline]"
    chart += "chart.render('#{chart_div}');[newline]"
    chart += "</script>[newline]"

    chart += "<span id='fcexp#{chart_div}' align='center'></span>[newline]"
    chart += "<script type='text/javascript'>[newline]"
    chart += "var myExportComponent = new FusionChartsExportObject('exporter#{chart_div}','/Charts/FCExporter.swf');[newline]"
    chart += "myExportComponent.Render('fcexp#{chart_div}');[newline]"
    chart += "</script>[newline]"
    return chart
  end

  def add_caar_chart_section(labels, caar, event_index, chart_div, width, height)
    chart = "<span id='#{chart_div}'>Now Loading...</span>[newline]"
    chart += "<script type='text/javascript'>[newline]"
    chart += "var chart = new FusionCharts('/Charts/ZoomLine.swf','Chart#{chart_div}','#{width}','#{height}','0','1');[newline]"
    chart += "chart.setXMLData(\"#{caar_chart_xml(labels, caar, event_index, chart_div, 1)}\");[newline]"
    chart += "chart.render('#{chart_div}');[newline]"
    chart += "</script>[newline]"

    chart += "<span id='fcexp#{chart_div}' align='center'></span>[newline]"
    chart += "<script type='text/javascript'>[newline]"
    chart += "var myExportComponent = new FusionChartsExportObject('exporter#{chart_div}','/Charts/FCExporter.swf');[newline]"
    chart += "myExportComponent.Render('fcexp#{chart_div}');[newline]"
    chart += "</script>[newline]"
    return chart
  end

  def aar_chart_xml(labels, aar, event_index, chart_div, export_flag)
    e_word = ""
    if export_flag==1
      e_word = " exportFileName='AAR#{chart_div}' exportEnabled='1' exportAtClient='1' exportHandler='exporter#{chart_div}'"
    end
    xml = "<chart#{e_word} decimals='4' compactDataMode='1' dataSeparator='|' palette='3' caption='AAR Diagram' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
    xml += "<categories>"
    xml += labels.join('|')
    xml += "</categories>"
    xml += "<dataset seriesName='AAR'>"
    xml += aar.join('|')
    xml += "</dataset>"
    xml += "<trendlines><line startvalue='0'/></trendlines>"
    xml += "<vTrendlines><line startIndex='#{event_index}' displayValue='Event Date' displayAlways='1'/></vTrendlines>"
    xml += "</chart>"
    return xml
  end

  def caar_chart_xml(labels, caar, event_index, chart_div, export_flag)
    e_word = ""
    if export_flag==1
      e_word = " exportFileName='CAAR#{chart_div}' exportEnabled='1' exportAtClient='1' exportHandler='exporter#{chart_div}'"
    end
    xml = "<chart#{e_word} decimals='4' compactDataMode='1' dataSeparator='|' palette='3' caption='CAAR Diagram' subCaption='' connectNullData='0' formatNumber='1' formatNumberScale='1'>"
    xml += "<categories>"
    xml += labels.join('|')
    xml += "</categories>"
    xml += "<dataset seriesName='CAAR'>"
    xml += caar.join('|')
    xml += "</dataset>"
    xml += "<trendlines><line startvalue='0'/></trendlines>"
    xml += "<vTrendlines><line startIndex='#{event_index}' displayValue='Event Date' displayAlways='1'/></vTrendlines>"
    xml += "</chart>"
    return xml
  end

  def cal_ri_cal(coeffs, const, r_hash, leadlag_size, total_size)
    ri_cal = Array.new
    for i in 0..total_size-1 do
      cal = 0.0
      cal += const
      for loop in (leadlag_size*-1)..leadlag_size do
        var_name = ""
        if loop<0
          var_name =  "Rm_#{loop*-1}"
        else
          var_name =  "Rm#{loop}"
        end
        if r_hash[var_name]
          cal += coeffs[var_name] * r_hash[var_name].to_a[i]
          ri_cal[i] = cal
        else
          ri_cal[i] = nil
        end
      end
    end
    return ri_cal
  end

  def get_sw_result(project_setting, running_stocks, market_stock_id, market_stock_type)
    require 'statsample'
    result = Array.new
    result = result << "<h3>Scholes-Williams</h3>"
    result = result << "Estimated Coefficients<hr/>"
    ar_all = Hash.new
    car_all = Hash.new
    sr_all = Hash.new
    rank_all = Hash.new
    aar = Array.new
    caar = Array.new
    compute_word = Array.new
    leadlag_size = 0
    if project_setting.leadlag_size
      leadlag_size = project_setting.leadlag_size
    end
    event_size = project_setting.max_event - project_setting.min_event + 1
    estimation_size = project_setting.max_est - project_setting.min_est + 1 - (leadlag_size*2)
    running_stocks.each_with_index do |rs,j|
      est_rm = Hash.new
      event_rm = Hash.new
      est_ri = nil
      event_ri = nil
      est_stock = Array.new
      est_market = Array.new
      event_stock = Array.new
      event_market = Array.new
      stock_symbol = 'S'
      if rs.stock_type=='S'
        stock_symbol = rs.stock.s_symbol
        est_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        est_ri = est_stock[leadlag_size..est_stock.size-1-leadlag_size]
        event_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_ri = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      else
        stock_symbol = UserStock.find(rs.user_stock_id).s_symbol
        est_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        est_ri = est_stock[leadlag_size..est_stock.size-1-leadlag_size]
        event_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_ri = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      end
      if market_stock_type=="System's"
        est_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        for loop in (leadlag_size*-1)..leadlag_size do
          if loop<0
            est_rm["Rm_#{loop*-1}"] = est_market[(leadlag_size+loop)..(est_stock.size-1-leadlag_size+loop)].to_scale
            event_rm["Rm_#{loop*-1}"] = event_market[(leadlag_size+loop)..(event_stock.size-1-leadlag_size+loop)].to_scale
          else
            est_rm["Rm#{loop}"] = est_market[(leadlag_size+loop)..(est_stock.size-1-leadlag_size+loop)].to_scale
            event_rm["Rm#{loop}"] = event_market[(leadlag_size+loop)..(event_stock.size-1-leadlag_size+loop)].to_scale
          end
        end
      else
        est_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        for loop in (leadlag_size*-1)..leadlag_size do
          if loop<0
            est_rm["Rm_#{loop*-1}"] = est_market[(leadlag_size+loop)..(est_stock.size-1-leadlag_size+loop)].to_scale
            event_rm["Rm_#{loop*-1}"] = event_market[(leadlag_size+loop)..(event_stock.size-1-leadlag_size+loop)].to_scale
          else
            est_rm["Rm#{loop}"] = est_market[(leadlag_size+loop)..(est_stock.size-1-leadlag_size+loop)].to_scale
            event_rm["Rm#{loop}"] = event_market[(leadlag_size+loop)..(event_stock.size-1-leadlag_size+loop)].to_scale
          end
        end
      end
      ds = est_rm.to_dataset
      ds['Ri'] = est_ri.to_scale
      lr = nil
      begin
        lr = Statsample::Regression.multiple(ds,'Ri')
      rescue
      end
      if lr
        coeffs = lr.coeffs
        const = lr.constant
        eq_word = "Ri = #{'%.4f' % const}"
        real_eq = "#{const}"
        for loop in (leadlag_size*-1)..leadlag_size do
          var_name = ""
          if loop<0
            var_name =  "Rm_#{loop*-1}"
          else
            var_name =  "Rm#{loop}"
          end
          if coeffs[var_name]>=0
            eq_word += "+#{'%.4f' % coeffs[var_name]}#{var_name}"
            real_eq += "+#{coeffs[var_name]}*#{var_name}"
          else
            eq_word += "#{'%.4f' % coeffs[var_name]}#{var_name}"
            real_eq += "#{coeffs[var_name]}*#{var_name}"
          end
        end
  #      puts real_eq
        eq_word += ", r^2 = #{'%.4f' % lr.r2}"
        result = result << "#{stock_symbol}: #{eq_word}"

#        ds2 = event_rm.to_dataset
#        ri_cal = ds2.compute(real_eq).to_a
        ri_cal = cal_ri_cal(coeffs, const, event_rm, leadlag_size, event_size)
        ri_cal2 = cal_ri_cal(coeffs, const, est_rm, leadlag_size, estimation_size)

        ar_array = Array.new
        car_array = Array.new
        sr_array = Array.new
        rank_array = Array.new
        total_ar = Array.new
        sse = cal_sse(est_rm["Rm0"].to_a)
        amr = cal_amr(est_rm["Rm0"].to_a)
        sde = cal_sde_sw(est_ri, ri_cal2)
        
        est_ri.each_with_index do |es,i|
          total_ar = total_ar << es - ri_cal2[i]
        end
        event_ri.each_with_index do |es,i|
          ar_array[i] = es - ri_cal[i]
          total_ar = total_ar << es - ri_cal[i]
          sr_array[i] = cal_sre(ar_array[i], sse, amr, sde, event_rm["Rm0"].to_a[i], est_ri.size)
        end
        rank_array = cal_rank(total_ar)
        ar_array.each_with_index do |ar,i|
          if i==0
            car_array[i] = ar
          else
            car_array[i] = car_array[i-1] + ar
          end
        end
        compute_word = compute_word << "s#{j}"
        ar_all["s#{j}"] = ar_array
        car_all["s#{j}"] = car_array
        sr_all["s#{j}"] = sr_array
        rank_all["s#{j}"] = rank_array
      else
        result = result << "#{stock_symbol}: Error in Estimation Process, Excluded from Calculation"
      end
    end

    min_event_date = project_setting.min_event

    for i in 1..event_size do
      mean = 0
      mean2 = 0
      total1 = 0
      total2 = 0
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          mean += ar_all["s#{j}"][i-1]
          total1 += 1
        end
        if car_all["s#{j}"]
          mean2 += car_all["s#{j}"][i-1]
          total2 += 1
        end
      end
      mean = mean/total1
      mean2 = mean2/total2
      aar[i-1] = mean
      caar[i-1] = mean2
    end

    table = "<font color='red'>*** : sig. at &alpha;=0.01, ** : sig. at &alpha;=0.05, * : sig. at &alpha;=0.1</font>"
    table += "<table class='basic_table'>"
    table += "<tr align='center'><th>Day</th><th>AAR</th>"
    if project_setting.aar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    table += "<th>CAAR</th>"
    if project_setting.caar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    if project_setting.sign_test=='Y'
      table += "<th>Sign Test<br/>(t)</th>"
    end
    if project_setting.rank_test=='Y'
      table += "<th>Rank Test<br/>(t)</th>"
    end
    if project_setting.sd_ar_test=='Y'
      table += "<th>Standardized<br/>abnormal return(t)</th>"
    end
    if project_setting.sd_cr_test=='Y'
      table += "<th>Standardized<br/>cross-sectional return(t)</th>"
    end
    table += "</tr>"
    labels = Array.new
    event_index = 0
    for i in 1..event_size do
      table += "<tr align='right'>"
      labels = labels << "#{min_event_date+i-1}"
      if  min_event_date+i-1==0
        event_index = i
      end
      table += "<td align='center'>#{min_event_date+i-1}</td>"
      table += "<td>#{begin '%.4f' % aar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          t_v[j] = ar_all["s#{j}"][i-1]
        end
      end

      if project_setting.aar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-(leadlag_size*2)-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end

      table += "<td>#{begin '%.4f' % caar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if car_all["s#{j}"]
          t_v[j] = car_all["s#{j}"][i-1]
        end
      end

      if project_setting.caar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-(leadlag_size*2)-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end
      if project_setting.sign_test=='Y'
        table += "<td>#{cal_signtest(ar_all,i-1)}</td>"
      end
      if project_setting.rank_test=='Y'
        table += "<td>#{cal_ranktest(rank_all,i-1,estimation_size,event_size)}</td>"
      end
      if project_setting.sd_ar_test=='Y'
        table += "<td>#{cal_partell(sr_all,i-1,estimation_size,(leadlag_size*2)+2)}</td>"
      end
      if project_setting.sd_cr_test=='Y'
        table += "<td>#{cal_boehmer(sr_all,i-1,(leadlag_size*2)+2)}</td>"
      end

      table += "</tr>"
    end
    table += "</table>"

    result = result << ""
    result = result << "Test Results<hr/>"
    result = result << table
    result = result << ""
    if project_setting.aar_diagram=='Y'
      begin
        result = result << add_aar_chart_section(labels, aar, event_index, 'aar_sw', 600, 350)
      rescue
        result = result << "Error in AAR Diagram"
      end
    end
    if project_setting.caar_diagram=='Y'
      begin
        result = result << add_caar_chart_section(labels, caar, event_index, 'caar_sw', 600, 350)
      rescue
        result = result << "Error in CAAR Diagram"
      end
    end
    result = result << ""
    if project_setting.ar=='Y'
      begin
        result = result << add_ar_table(ar_all, running_stocks, event_size, min_event_date, "AR Table")
      rescue
        result = result << "Error in AR table"
      end
    end
    result = result << ""
    if project_setting.car=='Y'
      begin
        result = result << add_ar_table(car_all, running_stocks, event_size, min_event_date, "CAR Table")
      rescue
        result = result << "Error in CAR table"
      end
    end
    result = result << ""
    return result.join("\n")
  end

  def get_bn_result(project_setting, running_stocks, market_stock_id, market_stock_type)
    result = Array.new
    result = result << "<h3>Beveridge-Nelson Decomposition</h3>"
    result = result << "Estimate Coefficients<hr/>"
    result = result << "Under Construction!"
    result = result << ""
    return result.join("\n")
  end

  def get_hm_result(project_setting, running_stocks, market_stock_id, market_stock_type)
    result = Array.new
    result = result << "<h3>Hamada</h3>"
    result = result << "Estimated Coefficients<hr/>"
    ar_all = Hash.new
    car_all = Hash.new
    sr_all = Hash.new
    rank_all = Hash.new
    aar = Array.new
    caar = Array.new
    compute_word = Array.new
    leadlag_size = 0
    if project_setting.leadlag_size
      leadlag_size = project_setting.leadlag_size
    end
    running_stocks.each_with_index do |rs,j|
      est_stock = Array.new
      est_market = Array.new
      event_stock = Array.new
      event_market = Array.new
      stock_symbol = 'S'
      if rs.stock_type=='S'
        stock_symbol = rs.stock.s_symbol
        est_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        event_stock_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", rs.stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_stock = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      else
        stock_symbol = UserStock.find(rs.user_stock_id).s_symbol
        est_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_est_date, rs.max_est_date], :order=>"trade_date")
        est_stock = est_stock_data.collect{|x| x.daily_return}
        event_stock_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", rs.user_stock_id, rs.min_event_date, rs.max_event_date], :order=>"trade_date")
        event_stock = event_stock_data.collect{|x| x.daily_return}
        event_stock = event_stock[leadlag_size..event_stock.size-1-leadlag_size]
      end
      if market_stock_type=="System's"
        est_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = StockTrade.find(:all, :conditions=>["stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        event_market = event_market[leadlag_size..event_market.size-1-leadlag_size]
      else
        est_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_est_date, rs.market_max_est_date], :order=>"trade_date")
        est_market = est_market_data.collect{|x| x.daily_return}
        event_market_data = UserStockTrade.find(:all, :conditions=>["user_stock_id=? AND trade_date>=? AND trade_date<=?", market_stock_id, rs.market_min_event_date, rs.market_max_event_date], :order=>"trade_date")
        event_market = event_market_data.collect{|x| x.daily_return}
        event_market = event_market[leadlag_size..event_market.size-1-leadlag_size]
      end
      sr = nil
      begin
        sr = Statsample::Regression.simple(est_market.to_scale, est_stock.to_scale)
      rescue
      end
      sign = ''
      sign2 = ''
      if sr
        before_de = rs.est_de
        after_de = rs.event_de
        tax_rate = project_setting.tax_rate
        bl = sr.b
        bu = bl/(1.0+((1.0-tax_rate)*before_de))
        bl = bu*(1.0+((1.0-tax_rate)*after_de))
        if sr.b>=0
          sign = '+'
        end
        if bl>=0
          sign2 = '+'
        end
        result = result << "#{stock_symbol}: Before=> Ri = #{'%.4f' % sr.a}#{sign}#{'%.4f' % sr.b}Rm, r^2 = #{'%.4f' % sr.r2}, After=>Ri = #{'%.4f' % sr.a}#{sign2}#{'%.4f' % bl}Rm"
        ar_array = Array.new
        car_array = Array.new
        sr_array = Array.new
        rank_array = Array.new
        total_ar = Array.new
        sse = cal_sse(est_market)
        amr = cal_amr(est_market)
        sde = cal_sde(est_stock, est_market, sr.a, bl)
        est_stock.each_with_index do |es,i|
          ri_cal = sr.a + (est_market[i] * bl)
          total_ar = total_ar << es - ri_cal
        end
        event_stock.each_with_index do |es,i|
          ri_cal = sr.a + (event_market[i] * bl)
          ar_array[i] = es - ri_cal
          total_ar = total_ar << es - ri_cal
          sr_array[i] = cal_sre(ar_array[i], sse, amr, sde, event_market[i], est_stock.size)
        end
        rank_array = cal_rank(total_ar)
        ar_array.each_with_index do |ar,i|
          if i==0
            car_array[i] = ar
          else
            car_array[i] = car_array[i-1] + ar
          end
        end
        compute_word = compute_word << "s#{j}"
        ar_all["s#{j}"] = ar_array
        car_all["s#{j}"] = car_array
        sr_all["s#{j}"] = sr_array
        rank_all["s#{j}"] = rank_array
      else
        result = result << "#{stock_symbol}: Error in Estimation Process, Excluded from Calculation"
      end
    end

    min_event_date = project_setting.min_event
    event_size = project_setting.max_event - project_setting.min_event + 1
    estimation_size = project_setting.max_est - project_setting.min_est + 1

    for i in 1..event_size do
      mean = 0
      mean2 = 0
      total1 = 0
      total2 = 0
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          mean += ar_all["s#{j}"][i-1]
          total1 += 1
        end
        if car_all["s#{j}"]
          mean2 += car_all["s#{j}"][i-1]
          total2 += 1
        end
      end
      mean = mean/total1
      mean2 = mean2/total2
      aar[i-1] = mean
      caar[i-1] = mean2
    end

    table = "<font color='red'>*** : sig. at &alpha;=0.01, ** : sig. at &alpha;=0.05, * : sig. at &alpha;=0.1</font>"
    table += "<table class='basic_table'>"
    table += "<tr align='center'><th>Day</th><th>AAR</th>"
    if project_setting.aar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    table += "<th>CAAR</th>"
    if project_setting.caar_t=='Y'
      table += "<th>t-test<br/>(t)</th>"
    end
    if project_setting.sign_test=='Y'
      table += "<th>Sign Test<br/>(t)</th>"
    end
    if project_setting.rank_test=='Y'
      table += "<th>Rank Test<br/>(t)</th>"
    end
    if project_setting.sd_ar_test=='Y'
      table += "<th>Standardized<br/>abnormal return(t)</th>"
    end
    if project_setting.sd_cr_test=='Y'
      table += "<th>Standardized<br/>cross-sectional return(t)</th>"
    end
    table += "</tr>"

    labels = Array.new
    event_index = 0
    for i in 1..event_size do
      table += "<tr align='right'>"
      labels = labels << "#{min_event_date+i-1}"
      if  min_event_date+i-1==0
        event_index = i
      end
      table += "<td align='center'>#{min_event_date+i-1}</td>"
      table += "<td>#{begin '%.4f' % aar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if ar_all["s#{j}"]
          t_v[j] = ar_all["s#{j}"][i-1]
        end
      end

      if project_setting.aar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end

      table += "<td>#{begin '%.4f' % caar[i-1] rescue '' end}</td>"

      t_v = Array.new
      running_stocks.each_with_index do |rs,j|
        if car_all["s#{j}"]
          t_v[j] = car_all["s#{j}"][i-1]
        end
      end

      if project_setting.caar_t=='Y'
        t_test = nil
        begin
          t_test = Statsample::Test::T::OneSample.new(t_v.to_scale, {:u=>0})
        rescue
        end
        if t_test
          table += "<td align='center'>#{get_t_test_star(t_test.df-1, t_test.t)} #{begin '%.4f' % t_test.t rescue '' end}</td>"
        else
          table += "<td align='center'>Error</td>"
        end
      end
      if project_setting.sign_test=='Y'
        table += "<td>#{cal_signtest(ar_all,i-1)}</td>"
      end
      if project_setting.rank_test=='Y'
        table += "<td>#{cal_ranktest(rank_all,i-1,estimation_size,event_size)}</td>"
      end
      if project_setting.sd_ar_test=='Y'
        table += "<td>#{cal_partell(sr_all,i-1,estimation_size,2)}</td>"
      end
      if project_setting.sd_cr_test=='Y'
        table += "<td>#{cal_boehmer(sr_all,i-1,2)}</td>"
      end

      table += "</tr>"
    end
    table += "</table>"

    result = result << ""
    result = result << "Test Results<hr/>"
    result = result << table
    result = result << ""
    if project_setting.aar_diagram=='Y'
      begin
        result = result << add_aar_chart_section(labels, aar, event_index, 'aar_hm', 600, 350)
      rescue
        result = result << "Error in AAR Diagram"
      end
    end
    if project_setting.caar_diagram=='Y'
      begin
        result = result << add_caar_chart_section(labels, caar, event_index, 'caar_hm', 600, 350)
      rescue
        result = result << "Error in CAAR Diagram"
      end
    end
    result = result << ""
    if project_setting.ar=='Y'
      begin
        result = result << add_ar_table(ar_all, running_stocks, event_size, min_event_date, "AR Table")
      rescue
        result = result << "Error in AR table"
      end
    end
    result = result << ""
    if project_setting.car=='Y'
      begin
        result = result << add_ar_table(car_all, running_stocks, event_size, min_event_date, "CAR Table")
      rescue
        result = result << "Error in CAR table"
      end
    end
    result = result << ""
    return result.join("\n")
  end

end
